package com.lovo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.bean.UserBean;
import com.lovo.sercive.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService service;

    @RequestMapping("login")
    public String login(String userName, String password, HttpServletRequest req){
        UserBean user=service.login(userName, password);
        if (user!=null){
            req.getSession().setAttribute("loginUser",user);
            return "ok";
        }else{
            return "no";
        }
    }
    @RequestMapping("getLoginUser")
    public UserBean getLoginUser(HttpServletRequest req){
        UserBean user = (UserBean)req.getSession().getAttribute("loginUser");
        return user;
    }
    @RequestMapping("add")
    public String add(@Valid UserBean user, BindingResult br) throws JsonProcessingException {
        if (br.hasErrors()) {//判断是否有验证失败的信息
            //得到校验失败集合
            List<FieldError> errorList = br.getFieldErrors();
            //将校验失败转化为JSON字符串发送给客户端
            ObjectMapper om = new ObjectMapper();
            String errorInfo = om.writeValueAsString(errorList);
            return errorInfo;
        }
        service.add(user);
        return "ok";
    }
}
